export default class SocketService {
    /*
    *单例设计模式
    */
    static instance = null;
    ws = null;
    callBackMapping = {};
    //用来标识是否连接成功
    connected = false;
    //记录重试的次数
    sendRetryCount = 0;
    //重新连接的次数
    connectRetryCount = 0;

    static get Instance() {
        if (!this.instance) {
            this.instance = new SocketService();
        }
        return this.instance
    }

    //定义连接服务器的方法
    connect() {
        //判断浏览器是否支持WebSocket
        if (!window.WebSocket) {
            return console.log("您的浏览器不支持WebSocket");
        }
        this.ws = new WebSocket("ws://localhost:9998");

        //连接成功的事件
        this.ws.onopen = () => {
            console.log("连接服务端成功");
            this.connected = true;
            this.connectRetryCount = 0;
        }
        //1.连接失败的事件 2.当连接成功后，服务器关闭
        this.ws.onclose = () => {
            this.connected = false;
            this.connectRetryCount++;
            console.log("连接服务端失败");
            setTimeout(() => {
                this.connect();
            }, this.connectRetryCount * 500);
        }
        //给服务器发送数据的事件
        this.ws.onmessage = (msg) => {
            // console.log("获取到服务端的数据", msg.data);
            const recvData = JSON.parse(msg.data);
            const socketType = recvData.socketType;
            //判断回调函数是否存在
            if (this.callBackMapping[socketType]) {
                const action = recvData.action;
                if (action === "getData") {
                    const realData = JSON.parse(recvData.data);
                    this.callBackMapping[socketType].call(this, realData);
                } else if (action === "fullScreen") {
                    this.callBackMapping[socketType].call(this, recvData);
                } else if (action === "themeChange") {
                    this.callBackMapping[socketType].call(this, recvData);
                }
            }
        }
    }

    //回调函数的注册
    registerCallBack(socketType, callback) {
        // console.log(socketType);
        this.callBackMapping[socketType] = callback;
    }

    //某一个回调函数的取消
    removeCallBack(socketType) {
        this.callBackMapping[socketType] = null;
    }

    //发送数据
    send(data) {
        //判断是否连接成功
        if (this.connected) {
            this.sendRetryCount = 0;
            this.ws.send(JSON.stringify(data));
        } else {
            this.sendRetryCount++;
            setTimeout(() => {
                this.send(data);
            }, 500 * this.sendRetryCount)
        }
    }
}